class Server {
  constructor() {
    this.http = require('http')
    this.server = this.http.createServer()
    this.url = require('url')
    this.fs = require('fs')
    this.storgeOrigin = 'https://browniu-dbc-1257187612.cos.ap-shanghai.myqcloud.com/'
  }
  init() {
    this.server.listen(2333, () => {
      console.log('服务器已启动：http://127.0.0.1:2333/')
    })
    this.server.on('request', (req, res) => {
      this.setHeader(res)
      this.request(req, res)
    })
  }
  request(req, res) {
    let port = this.url.parse(req.url, true).pathname
    if (port.match('getList')) {
      this.fs.readFile('../list/cloudSave.json', (err, data) => {
        if (err) console.log(err)
        let list = JSON.parse(data.toString())
        list = list.map(e => this.storgeOrigin + e)
        res.end(JSON.stringify(list))
      })
    } else if (port.match('itemLike')) {
      let data = ''
      req.on('data', (chunk) => {
        data += chunk
      })
      req.on('end', () => {
        res.end('请求提交数据接口成功,' + data)
        console.log(data)
      })
    } else {
      res.end('404')
    }
  }
  setHeader(res) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Headers", "Origin,No-Cache,X-Requested-With,If-Modified-Since,Pragma,Last-Modified,Cache-Control,Expires,Content-Type,Access-Control-Allow-Credentials");
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,OPTIONS");
    res.setHeader("Content-Type", "text/plain; charset=utf-8");
  }

}

let server = new Server()
server.init()